import platform
import subprocess
import time
import zipfile
from sqlalchemy import select, update
from fastapi import APIRouter, status
import requests

from core.exceptions import NormalException
from core.database import getDB
from schemas.base import R
from schemas.system import InfoOutSchema
from models.base import SystemInfoTable


router = APIRouter(prefix="/system", tags=["系统信息接口"])


@router.get(
    "/",
    summary="获取网关基础信息"
)
def getInfo():
    with getDB() as db:
        result = db.scalars(select(SystemInfoTable)).one()
        return R(data=result.dict())


@router.put(
    "/",
    summary="修改网关基础信息"
)
def updateInfo(data: InfoOutSchema):
    with getDB() as db:
        db.execute(update(SystemInfoTable).values(data.model_dump()))
        db.commit()
    return R()


@router.post(
    "/reloadArgs/",
    summary="重载参数"
)
def reloadArgs():
    if platform.system() != "Linux":
        raise NormalException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="当前系统不支持于网页上进行重载"
        )
    proc = subprocess.run("supervisorctl restart gateway-server", shell=True)
    if proc.returncode == 0:
        return R()
    else:
        raise NormalException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="重载失败，请稍后重试"
        )


@router.post(
    "/reboot/",
    summary="重启网关"
)
def reboot():
    if platform.system() != "Linux":
        raise NormalException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="当前系统不支持于网页上重启网关"
        )
    proc = subprocess.run("reboot", shell=True)
    if proc.returncode == 0:
        return R()
    else:
        raise NormalException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="重启失败，请稍后重试"
        )


@router.post(
    "/update/",
    summary="网关发起升级"
)
def updateGateway():
    url = "http://172.80.10.150/download/gateway/software.zip"
    fileName = f"template/temp/{int(time.time())}-gateway.zip"
    req = requests.get(url=url, stream=True)
    # 保存压缩文件
    with open(fileName, "wb") as f:
        for bl in req.iter_content(chunk_size=1024):
            if bl:
                f.write(bl)
    # 删除原始代码
    srcFile = "/home/orangepi/gateway-server"
    proc = subprocess.run("rm -rf /home/orangepi/gateway-server", shell=True)
    if proc.returncode != 0:
        raise NormalException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="原始项目删除失败"
        )
    file = zipfile.ZipFile(fileName)
    zipExtract = file.extractall(srcFile)
    zipExtract.close()
    proc = subprocess.run("supervisorctl restart gateway-server", shell=True)
    if proc.returncode != 0:
        raise NormalException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="项目重启失败，请手动重启项目"
        )
    return R()
